package mygang.controller.manager;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mygang.controller.AbstractController;
import mygang.helper.ControllerHelper;
import mygang.helper.JsonHelper;
import mygang.helper.Utils;
import mygang.model.constructor.Form;
import mygang.model.constructor.FormType;
import mygang.model.constructor.Step;
import mygang.model.constructor.field.Field;
import mygang.service.ConstructorService;
import mygang.service.manager.FieldService;
import mygang.service.manager.WizardService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 04/03/2013
 */
@Controller
@RequestMapping(AbstractController.MANAGE_WIZARD)
public class WizardController extends AbstractManageController<WizardService, Form> {
    private static final Logger log = Logger.getLogger(WizardController.class.toString());
    
    @Autowired
    private FieldService fieldService;
    
    @Autowired
    private ConstructorService constructorService;

    Form prepareObject(HttpServletRequest request) throws Exception {
        String tempId = request.getParameter("id");
        Long id = tempId!=null && !tempId.isEmpty() ? new Long(tempId) : null;
        
        String title = request.getParameter("title");
        if(title==null || title.isEmpty()) {
            throw new Exception("Title is not specified");
        }
        String desc = request.getParameter("desc");
        tempId = request.getParameter("type");
        Long typeId = tempId!=null && !tempId.isEmpty() ? new Long(tempId) : null;
        
        if(typeId==null) {
            throw new Exception("Type is not selected");
        }
        FormType type = getService().getTypeById(typeId.longValue());
        log.debug(type.getId()+" ---- "+type.getName());
        
        return id==null ? new Form(type, title, desc) : new Form(id.longValue(), type, title, desc);
    }

    String getLink() {
        return MANAGE_WIZARD;
    }
    
    @RequestMapping(value = "/types", method = RequestMethod.POST)
    public void getTypes(HttpServletResponse response) throws IOException {
        JsonHelper.prepareJsonResponse(Utils.convertToOptions(getService().getTypes()), response);
    }
    
    @RequestMapping(value = "/c", method = RequestMethod.GET)
    public ModelAndView compose(@RequestParam(required = true, value = "id") Long id){
        ModelAndView model = new ModelAndView(getLink()+"Compose");
        model.addObject("obj", getService().getById(id.longValue()));
        return model;
    }
    
    @RequestMapping(value = "/s/a", method = RequestMethod.GET)
    public ModelAndView addEditStep(){
        return new ModelAndView(getLink()+"StepAddEdit");
    }
    
    @RequestMapping(value = "/f/a", method = RequestMethod.GET)
    public ModelAndView addEditField(){
        return new ModelAndView(getLink()+"FieldAddEdit");
    }
    
    @RequestMapping(value = "/getFields", method = RequestMethod.POST)
    public void getFields(HttpServletResponse response) throws IOException {
        JsonHelper.prepareJsonResponse(Utils.convertToOptions(fieldService.getAll()), response);
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public @ResponseBody String saveWizard(@RequestParam(required = true, value = "wizard") String wizard) throws IOException {
        try{
            log.debug(wizard);
            // prepares all variables
            Gson gson = new Gson();
            JsonParser jsonParser = new JsonParser();
            
            JsonElement jsonElement = jsonParser.parse(wizard);
            if(jsonElement.isJsonObject()){
                Form formFromJson = gson.fromJson(wizard, Form.class);
                Form form = getService().getById(formFromJson.getId());
                form.setSteps(formFromJson.getSteps());
                formFromJson = null;
                getService().save(form);
            }
            return "ok";
        } catch (Exception ex){
            ex.printStackTrace();
            return ex.getMessage();
        }
    }
    
    @Override
    public void save(HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            Form form = getObject(request);
            Form temp = getService().getById(form.getId());
            if(temp!=null) form.setSteps(temp.getSteps());
            getService().save(form);
            ControllerHelper.success(response);
        } catch (Exception ex) {
            ControllerHelper.handleException(ex, response);
        }
    }
}